#include <viewConf.h>
#include <broadcast.h>

namespace View {

  ViewConf *ViewConf::instance = NULL;
  
  ViewConf::ViewConf()
 {
   ReadConfFile();
 }

  ViewConf::~ViewConf()
  {

  }

  bool ViewConf::ReadConfFile()
  {
    std::string path;
    using namespace Model;
    ModelConf *conf = ModelConf::GetModelConf();
    Controller::Language language = 
      static_cast<Controller::Language>(conf->GetDoubleData("UILanguage"));
    if(Controller::LANGUAGE_CHINA == language)
      path = VIEW_CONF_PATH + (std::string)"conf/Strings_zh_CN.conf";    
    else if(Controller::LANGUAGE_USA == language)
      path = VIEW_CONF_PATH + (std::string)"conf/Strings_en_US.conf";
    else
      std::cout<<"error in read last choose language....\n";
    LoadStrings(path);
    path = VIEW_CONF_PATH + (std::string)"conf/UI.conf";    
    LoadUIConf(path);
    return true;
  }
  
  ViewConf *ViewConf::GetViewConf()
  {
    if( NULL == ViewConf::instance)
      ViewConf::instance = new ViewConf();
    return ViewConf::instance;
  }

  double ViewConf::GetDoubleData(const std::string &name)
  {
    return doubleData.find(name)->second;
  }

  std::string ViewConf::GetStringData(const std::string &name)
  {
    return stringData.find(name)->second;
  }

  bool ViewConf::LoadStrings(std::string path)
  {
    stringData.clear();
    std::ifstream in;
    std::string line;
    in.open( path.c_str());
    if(in.is_open()){
      while(getline(in,line)){
	if(' ' == line[0] || '#' == line[0] || 0 == line.size() )
	  continue;
	size_t pos = line.find(" ");
	std::string name = line.substr(0,pos);
	line = line.substr(pos + 1);
	stringData.insert( std::pair<std::string,std::string>(name,line) );
	//	std::cout<<"[ "<<name<<" ] = "<<size<<"\n";
      }
    }else{
      std::cout<<"failed in open file [ "<<path<<" ]\n";
      return false;
    }
    in.close();
    
    return true;
 }

  bool ViewConf::LoadUIConf(std::string path)
  {
    doubleData.clear();
    std::ifstream in;
    std::string line;

    in.open(path.c_str());
    if(in.is_open()){
      while(getline(in,line)){
	if(' ' == line[0] || '#' == line[0] || 0 == line.size() )
	  continue;
	size_t pos = line.find(" ");
	std::string name = line.substr(0,pos);
	line = line.substr(pos + 1);
	double size = atoi(line.c_str());
	doubleData.insert( std::pair<std::string,double>(name,size) );
	//	std::cout<<"[ "<<name<<" ] = "<<size<<"\n";
      }
    }else{
      std::cout<<"failed in open file [ "<<path<<" ]\n";
      return false;
    }
    in.close();

    return true;
  }

}
